import {Injectable} from '@angular/core';
import * as Keycloak from 'keycloak-js';
import {KeycloakInstance} from 'keycloak-js';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class KeycloakService {

  static keycloakAuth: KeycloakInstance = Keycloak('assets/keycloak.json');

  static init(options?: any): Promise<any> {
    return new Promise((resolve, reject) => {
      KeycloakService.keycloakAuth.init(options)
        .success(() => {
          resolve();
        })
        .error((errorData: any) => {
          reject(errorData);
        });
    });
  }

  static getToken(): Observable<string> {
    return Observable.create((observe) => {
      if (KeycloakService.keycloakAuth.token) {
        KeycloakService.keycloakAuth.updateToken(30) // refresh token if it will expire in 90 seconds or less
          .success(() => {
            observe.next(KeycloakService.keycloakAuth.token);
          })
          .error(() => {
            observe.error('Failed to refresh token');
          });
      } else {
        observe.error('Not logged in');
      }
    });
  }

  static authenticated(): boolean {
    return KeycloakService.keycloakAuth.authenticated;
  }

  static login() {
    KeycloakService.keycloakAuth.login();
  }

  static logout() {
    KeycloakService.keycloakAuth.logout();
  }

  static account() {
    KeycloakService.keycloakAuth.accountManagement();
  }

  static getUser(): User {
    return {
      username: '哪吒',
      age: 3
    };
  }
}
